package com.seari.utils;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ContextLifecycleScheduledTaskRegistrar;
import org.springframework.stereotype.Component;
import org.springframework.util.ErrorHandler;

import com.seari.main.BaseTaskStarter;

@Component
public class DynamicCronTasks {
	
	private Logger logger = LoggerFactory.getLogger(DynamicCronTasks.class);
	
	private static ContextLifecycleScheduledTaskRegistrar taskRegister;
	
	private static ThreadPoolTaskScheduler scheduler;
	
	private static Map<Runnable, String> cronTasks = new HashMap<Runnable, String>();
	
	
	public void init() {
		scheduler.setPoolSize(10);
		scheduler.initialize();
		scheduler.setErrorHandler(new ErrorHandler() {
			@Override
			public void handleError(Throwable t) {
				logger.error( "Caught exception in ScheduledExecutorService. StackTrace:\n" + t.getStackTrace() );
			}
		});
	}
	
	public void setCron(Runnable run,String s) {
		cronTasks.put(run, s);
	}
	
	public void schedulerTasks(Map<Runnable, String> cronTasks) {
		if(taskRegister != null) {
			taskRegister.destroy();
		}
		if(scheduler != null) {
			scheduler.destroy();
		}
		taskRegister =  new ContextLifecycleScheduledTaskRegistrar();
		scheduler = new ThreadPoolTaskScheduler();
		init();
		taskRegister.setScheduler(scheduler);
		if(cronTasks != null && cronTasks.size() > 0) {
			taskRegister.setCronTasks(cronTasks);
		}
		taskRegister.afterSingletonsInstantiated();
		
	}
	

}
